from wormbane.config.config import default_grid_size
from wormbane.model.cell import Cell
from wormbane.model.feature import char_to_feature
from wormbane.model.grid import Grid


def parse_level(path, size = default_grid_size):
    file = open(path)
    try:
        grid = Grid(size)
        width, height = size
        y = height - 1
        for line in file.readlines()[:height]:
            x = 0
            for char in line.rstrip()[:width]:
                try:
                    feature = char_to_feature(char)
                except KeyError, e:
                    raise LevelParseError(path, height - y, x + 1, char)
                grid[x, y].feature = feature
                x += 1
            y -= 1
        return grid
    finally:
        file.close()


class LevelParseError(Exception):
    def __init__(self, path, line, column, char):
        self.path = path
        self.line = line
        self.column = column
        self.char = char
        message = ('invalid character "%s" at line %d, column %d of file "%s"'
                   % (char, line, column, path))
        Exception.__init__(self, message)
